package com.time.store.order.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.time.store.core.util.AssertUtil;
import com.time.store.order.entity.bo.OrderAfterSale;
import com.time.store.order.entity.dto.AfterSalePageQuery;
import com.time.store.order.entity.dto.OrderPageExportReq;
import com.time.store.order.entity.dto.ReimburseDTO;
import com.time.store.order.service.OrderAfterSaleService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


/**
 * 订单售后控制器
 *
 * @description: 订单售后控制器
 * @menu 订单售后
 */
@RestController
@RequestMapping("/api/order/afterSale")
public class OrderAfterSaleController {
    @Autowired
    private OrderAfterSaleService orderAfterSaleService;

    /**
     * 分页查询
     *
     * @param afterSalePageQuery
     * @return
     * @status done
     */
    @GetMapping("/page")
    public Page<OrderAfterSale> page(@Validated AfterSalePageQuery afterSalePageQuery) {
        return orderAfterSaleService.pageAfterSale(afterSalePageQuery);
    }


    /**
     * 导出售后
     *
     * @param afterSalePageQuery
     * @return
     * @status done
     */
    @GetMapping("export")
    public void export(AfterSalePageQuery afterSalePageQuery, HttpServletResponse response) throws IOException {
        String fileName = URLEncoder.encode("售后报表", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xls\"");
        Workbook workbook = orderAfterSaleService.export(afterSalePageQuery);
        workbook.write(response.getOutputStream());
    }

    /**
     * 同意/拒绝退款
     *
     * @param reimburseDTO
     * @return
     * @status done
     */
    @PatchMapping("/reimburse")
    public void reimburse(@RequestBody @Validated ReimburseDTO reimburseDTO) {
        if (reimburseDTO.getIsAgree()) {
            AssertUtil.isTrue(StrUtil.isNotBlank(reimburseDTO.getReceiverProvince()), "收货人省必填");
            AssertUtil.isTrue(StrUtil.isNotBlank(reimburseDTO.getReceiverCity()), "收货人省必填");
            AssertUtil.isTrue(StrUtil.isNotBlank(reimburseDTO.getReceiverArea()), "收货人区/县必填");
            AssertUtil.isTrue(StrUtil.isNotBlank(reimburseDTO.getReceiverAddress()), "收货人详细地址必填");
        }
        orderAfterSaleService.reimburse(reimburseDTO);

    }
}
